package utils.commons;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.InetSocketAddress;
import java.net.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TestNetWork {
  private static final Logger log=LoggerFactory.getLogger(TestNetWork.class);

  //NOTICE 此方法与linux平台不兼容，可能造成无法预测的问题，待修改
  @Deprecated
	public static boolean connNetWork(String host,int port) {
		try {
			boolean success = false;
			Process pr = Runtime.getRuntime().exec("ping " + host + " -w 300 -n 2");
			InputStreamReader is = new InputStreamReader(pr.getInputStream());
			LineNumberReader linenumberreader = new LineNumberReader(is);
			String line=null;
			
			while (null!=(line=linenumberreader.readLine())) {
				if (line.contains("TTL")) {
					if (isOpen(host,port)){
						log.info("连接" + host +":"+port+ "端口畅通^^^^^^^^^^^^");	
						success = true;
						break;
					}else{
						log.info("连接" + host +":"+port+ "端口不通^^^^^^^^^^^^");	
						success = false;
						break;
					}
				}
			}
			linenumberreader.close();
			is.close();
			return success;
		} catch (Exception ex) {
			log.error("连接失败", ex);
			return false;
		}
	}
	
	private static int SOCKET_CONNECT_TIMEOUT=5000;
	
  //NOTICE 此方法与linux平台不兼容，可能造成无法预测的问题，待修改
	@Deprecated
	private static boolean isOpen(String host, int port) {
		try {
			Socket socket = new Socket();
			InetSocketAddress address=new InetSocketAddress(host,port);	
			socket.connect(address, SOCKET_CONNECT_TIMEOUT);				
			socket.close();
			return true;
		} catch (IOException e) {
			log.error("连接失败", e);
			return false;
		}
	}
	
	public static boolean isConnectable(final String host,final int port){
	  InetSocketAddress address=new InetSocketAddress(host,port);
    Socket socket = new Socket();
    try {
      socket.connect(address, SOCKET_CONNECT_TIMEOUT);
      socket.close();
    } catch (IOException e) {
    	log.error("连接失败", e);
      return false;
    }
    return true;
	}
}
